package com.example.week10homework;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends Activity {

	Button okBtn;
	EditText userNameET,pwdET;
	TextView tipTV;
	//食乐网登录地址
	String path = "http://www.sl777.cc/API/DataM/SQLData/userLogin";

	Handler handler = new Handler(){
		public void handleMessage(Message msg){
			if(msg.what==1){
				String userInfo = String.valueOf(msg.obj);
				JSONObject jo = (JSONObject) JSON.parse(userInfo);
				String joData = jo.getString("data");
				if("".equals(joData) ||"[]".equals(joData)){
					tipTV.setText("用户名或密码错误，登陆失败！");
				}else {
					Intent intent = new Intent(MainActivity.this, LoginOkActivity.class);
					intent.putExtra("userInfo", userInfo);
					startActivity(intent);
				}
			}else if(msg.what==0){
				tipTV.setText(String.valueOf(msg.obj));
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		userNameET  = (EditText)findViewById(R.id.c103userName);
		pwdET = (EditText)findViewById(R.id.c103pwd);
		okBtn= (Button)findViewById(R.id.c103okBtn);
		tipTV =(TextView)findViewById(R.id.c103tipTV);


		okBtn.getBackground().setAlpha(100);

		okBtn.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				final String userName = userNameET.getText().toString();
				final String pwd = pwdET.getText().toString();
				userNameET.setText("");
				pwdET.setText("");
				tipTV.setText("");
				if(userName.equals("")||pwd.equals("")){
					Toast.makeText(MainActivity.this, "用户名和密码不能为空", Toast.LENGTH_SHORT).show();
					return ;
				}
				Runnable runnable =new Runnable(){
					public void run(){
						try{
							URL url = new URL(path);
							HttpURLConnection connection = (HttpURLConnection) url.openConnection();
							connection.setRequestMethod("POST");//设置请求方式为POST
							connection.setDoOutput(true);//允许写出
							connection.setDoInput(true);//允许读入
							connection.setUseCaches(false);//不使用缓存
							connection.connect();
							String body = "Param={'where':'account="+userName+" and password="+pwd+"'}";
							BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
							writer.write(body);
							writer.close();

							int responseCode = connection.getResponseCode();
							if(responseCode == HttpURLConnection.HTTP_OK){
								InputStream inputStream = connection.getInputStream();
								String entityStr = is2String(inputStream);//将流转换为字符串
								Message msg = Message.obtain(handler, 1, entityStr);
								msg.sendToTarget();
							}else{
								Message msg = Message.obtain(handler, 0, "网络连接异常");
								msg.sendToTarget();
							}

						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				};

				new Thread(runnable).start();
			}
		});
	}


	public String is2String(InputStream is) throws IOException{

		//连接后，创建一个输入流来读取response
		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is,"utf-8"));
		String line = "";
		StringBuilder stringBuilder = new StringBuilder();
		//每次读取一行，若非空则添加至 stringBuilder
		while((line = bufferedReader.readLine()) != null){
			stringBuilder.append(line);
		}
		//读取所有的数据后，赋值给 response;
		String result = stringBuilder.toString().trim();
		return result;
	}
}

